<template>
  <el-card
    class="article-card"
    shadow="hover"
    :body-style="{ padding: '16px' }"
  >
    <div class="article-content">
      <!-- 文章封面 -->
      <div v-if="(article as any).coverImage" class="article-cover">
        <el-image
          :src="getImageUrl((article as any).coverImage)"
          fit="cover"
          :lazy="true"
          class="cover-image"
          @click="handleArticleClick($event)"
        >
          <template #error>
            <div class="image-error">
              <IconifyIconOnline icon="ep:picture" />
            </div>
          </template>
        </el-image>
      </div>

      <!-- 文章信息 -->
      <div class="article-info">
        <h3 class="article-title" @click="handleArticleClick($event)">
          {{ article.title }}
        </h3>

        <p class="article-summary">{{ article.summary }}</p>

        <!-- 文章标签 -->
        <div v-if="articleTags && articleTags.length > 0" class="article-tags">
          <el-tag
            v-for="tag in articleTags.slice(0, 3)"
            :key="tag.id"
            size="small"
            class="tag-item"
            :style="{
              backgroundColor: tag.color || '#909399',
              color: '#ffffff',
              border: `1px solid ${tag.color || '#909399'}`
            }"
          >
            {{ tag.name }}
          </el-tag>
          <el-tag
            v-if="articleTags.length > 3"
            size="small"
            class="tag-more"
            type="info"
          >
            +{{ articleTags.length - 3 }}
          </el-tag>
        </div>

        <!-- 作者信息 -->
        <div class="article-meta" :class="{ 'no-author': !article.authorName }">
          <div
            v-if="article.authorName"
            class="author-info"
            @click.stop="handleAuthorClick"
          >
            <el-avatar
              :src="getImageUrl(article.authorAvatar)"
              :size="24"
              class="author-avatar"
            >
              <IconifyIconOnline icon="ep:user" />
            </el-avatar>
            <span class="author-name">{{ article.authorName }}</span>
          </div>

          <!-- 时间信息在左侧 -->
          <div class="time-section">
            <span class="stat-item time-item">
              <IconifyIconOnline icon="ep:clock" />
              {{ formatTime(article.publishTime) }}
            </span>
            <span
              v-if="interactionTime"
              class="stat-item interaction-time-item"
            >
              <IconifyIconOnline icon="ep:calendar" />
              {{ interactionTimeLabel }}于 {{ formatTime(interactionTime) }}
            </span>
          </div>

          <!-- 统计信息在右侧 -->
          <div class="article-stats">
            <span class="stat-item">
              <IconifyIconOnline icon="ep:view" />
              {{ formatNumber(article.viewCount) }}
            </span>
            <span
              v-if="showLikeCount"
              class="stat-item"
              :class="{ interactive: showInteractiveLike }"
            >
              <LinearNewOhterLikeThumbUp
                class="like-icon"
                :class="{
                  clickable: showInteractiveLike,
                  loading: showInteractiveLike && actionLoading
                }"
                :title="showInteractiveLike ? '取消点赞' : ''"
                @click="showInteractiveLike ? handleLikeAction($event) : null"
              />
              {{ formatNumber(article.likeCount) }}
            </span>
            <span
              v-if="showCollectCount"
              class="stat-item"
              :class="{ interactive: showInteractiveCollect }"
            >
              <IconifyIconOnline
                icon="ep:star-filled"
                :class="{
                  clickable: showInteractiveCollect,
                  loading: showInteractiveCollect && actionLoading
                }"
                :title="showInteractiveCollect ? '取消收藏' : ''"
                @click="
                  showInteractiveCollect ? handleCollectAction($event) : null
                "
              />
              {{ formatNumber((article as any).collectCount || 0) }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { IconifyIconOnline } from "@/components/ReIcon";
import { LinearNewOhterLikeThumbUp } from "@element-extended-icon-pack/vue";
import type { Article } from "@/api/user-profile";
import type { ArticleCardItem } from "@/types/user-interactions";
import { formatNumber, formatTime } from "@/api/user-profile";
import { likeUserArticleApi, collectUserArticleApi } from "@/api/user-article";
import { useUserAuthStore } from "@/store/modules/userAuth";

interface Props {
  article: ArticleCardItem;
  interactionTime?: string;
  interactionTimeLabel?: string;
  showCollectCount?: boolean;
  /** 是否显示点赞统计 */
  showLikeCount?: boolean;
  /** 是否显示可交互的点赞图标 */
  showInteractiveLike?: boolean;
  /** 是否显示可交互的收藏图标 */
  showInteractiveCollect?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  interactionTime: "",
  interactionTimeLabel: "",
  showCollectCount: false,
  showLikeCount: true,
  showInteractiveLike: false,
  showInteractiveCollect: false
});

const router = useRouter();
const userAuthStore = useUserAuthStore();

// 响应式数据
const actionLoading = ref(false);

// 发射事件
const emit = defineEmits<{
  /** 文章被移除时触发 */
  removed: [articleId: number];
}>();

// 计算属性
const showCollectCount = computed(() => {
  return props.showCollectCount && "collectCount" in props.article;
});

// 处理文章标签
const articleTags = computed(() => {
  const article = props.article as any;
  console.log(`🏷️ ArticleCard 标签调试 - 文章ID: ${article.articleId}`, {
    articleTags: article.articleTags,
    tags: article.tags,
    tagList: article.tagList
  });

  // 优先使用 tagList（后端返回的标准字段）
  if (article.tagList && Array.isArray(article.tagList)) {
    console.log(`✅ 使用 tagList:`, article.tagList);
    return article.tagList;
  }
  // 其次使用 articleTags
  if (article.articleTags && Array.isArray(article.articleTags)) {
    console.log(`✅ 使用 articleTags:`, article.articleTags);
    return article.articleTags;
  }
  // 最后尝试 tags
  if (article.tags && Array.isArray(article.tags)) {
    console.log(`✅ 使用 tags:`, article.tags);
    return article.tags;
  }
  console.log(`❌ 没有找到有效的标签数据`);
  return [];
});

// 方法
const getImageUrl = (url: string): string => {
  if (!url) return "";
  if (url.startsWith("http")) return url;
  // 使用统一的基础API URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};

const handleArticleClick = (event?: Event) => {
  // 阻止默认行为和事件冒泡
  if (event) {
    event.preventDefault();
    event.stopPropagation();
  }

  console.log("🔗 点击文章，准备在新标签页打开:", props.article.articleId);

  // 以新标签页打开文章详情，符合主流论坛交互习惯
  const route = router.resolve(`/user/article/${props.article.articleId}`);
  // 使用完整URL，确保 Hash 模式路由正确解析
  const fullUrl =
    window.location.origin + window.location.pathname + route.href;
  console.log("🔗 完整URL:", fullUrl);

  const newWindow = window.open(fullUrl, "_blank");

  if (!newWindow) {
    console.warn("⚠️ 浏览器阻止了弹出窗口，尝试使用 router.push");
    router.push(`/user/article/${props.article.articleId}`);
  } else {
    console.log("✅ 成功在新标签页打开文章");
  }
};

// 处理作者点击
const handleAuthorClick = () => {
  const article = props.article as any;
  // 获取作者ID，支持多种字段名
  const authorId = article.authorId || article.author?.userId || article.userId;
  if (authorId) {
    console.log(`👤 点击作者，跳转到用户主页: ${authorId}`);
    router.push(`/user/profile/${authorId}`);
  } else {
    console.warn("❌ 作者ID不存在，无法跳转");
  }
};

// 处理点赞操作
const handleLikeAction = async (event: Event) => {
  event.stopPropagation();
  if (actionLoading.value) return;

  const article = props.article as any;
  // 在个人中心的点赞列表中，所有文章默认都是已点赞状态
  // 因此当用户点击时，应该是取消点赞（即传false）
  const currentLikedState =
    article.isLiked !== undefined ? article.isLiked : true;
  const newLikeState = !currentLikedState;

  console.log("🔵 点赞操作", {
    articleId: props.article.articleId,
    currentLikedState,
    newLikeState,
    isShowInteractiveLike: props.showInteractiveLike
  });

  try {
    actionLoading.value = true;
    const response = await likeUserArticleApi(
      props.article.articleId,
      newLikeState
    );

    if (response.code === 200) {
      // 更新本地状态
      if (article) {
        article.isLiked = newLikeState;
        article.likeCount = (article.likeCount || 0) + (newLikeState ? 1 : -1);
      }

      ElMessage.success(newLikeState ? "点赞成功" : "取消点赞成功");

      // 如果是取消操作且在个人资料页，触发removed事件
      if (!newLikeState && props.showInteractiveLike) {
        emit("removed", props.article.articleId);
      }
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("点赞操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    actionLoading.value = false;
  }
};

// 处理收藏操作
const handleCollectAction = async (event: Event) => {
  event.stopPropagation();
  if (actionLoading.value) return;

  const article = props.article as any;
  // 在个人中心的收藏列表中，所有文章默认都是已收藏状态
  // 因此当用户点击时，应该是取消收藏（即传false）
  const currentCollectedState =
    article.isCollected !== undefined ? article.isCollected : true;
  const newCollectState = !currentCollectedState;

  console.log("⭐ 收藏操作", {
    articleId: props.article.articleId,
    currentCollectedState,
    newCollectState,
    isShowInteractiveCollect: props.showInteractiveCollect
  });

  try {
    actionLoading.value = true;
    const response = await collectUserArticleApi(
      props.article.articleId,
      newCollectState
    );

    if (response.code === 200) {
      // 更新本地状态
      if (article) {
        article.isCollected = newCollectState;
        article.collectCount =
          (article.collectCount || 0) + (newCollectState ? 1 : -1);
      }

      ElMessage.success(newCollectState ? "收藏成功" : "取消收藏成功");

      // 如果是取消操作且在个人资料页，触发removed事件
      if (!newCollectState && props.showInteractiveCollect) {
        emit("removed", props.article.articleId);
      }
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    actionLoading.value = false;
  }
};
</script>

<style scoped lang="scss">
// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .article-card {
    .image-error {
      background: var(--el-bg-color-page);
    }
  }
}

.article-card {
  margin-bottom: 16px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 8px 25px rgb(0 0 0 / 10%);
    transform: translateY(-2px);

    .article-title {
      color: var(--el-color-primary);
    }
  }

  .article-content {
    display: flex;
    gap: 16px;

    @media (width <= 768px) {
      flex-direction: column;
      gap: 12px;
    }
  }

  .article-cover {
    flex-shrink: 0;
    width: 160px;
    height: 120px;

    @media (width <= 768px) {
      width: 100%;
      height: 180px;
    }

    .cover-image {
      width: 100%;
      height: 100%;
      overflow: hidden;
      cursor: pointer;
      border-radius: 8px;
      transition: transform 0.3s ease;

      &:hover {
        transform: scale(1.05);
      }
    }

    .image-error {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      color: var(--el-text-color-placeholder);
      background: var(--el-fill-color-light);
      border-radius: 8px;

      .iconify {
        font-size: 32px;
      }
    }
  }

  .article-info {
    flex: 1;
    min-width: 0;

    .article-title {
      // 标题截断
      display: -webkit-box;
      margin: 0 0 8px;
      overflow: hidden;
      -webkit-line-clamp: 2;
      font-size: 18px;
      font-weight: 600;
      line-height: 1.4;
      color: var(--el-text-color-primary);
      cursor: pointer;
      transition: color 0.3s ease;
      -webkit-box-orient: vertical;

      @media (width <= 768px) {
        -webkit-line-clamp: 2;
        font-size: 16px;
      }

      &:hover {
        color: var(--el-color-primary);
      }
    }

    .article-summary {
      // 内容截断
      display: -webkit-box;
      margin: 0 0 12px;
      overflow: hidden;
      -webkit-line-clamp: 2;
      font-size: 14px;
      line-height: 1.6;
      color: var(--el-text-color-regular);
      -webkit-box-orient: vertical;

      @media (width <= 768px) {
        -webkit-line-clamp: 3;
      }
    }

    .article-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 12px;

      @media (width <= 768px) {
        gap: 6px;
        margin-bottom: 10px;

        .tag-item {
          padding: 2px 6px;
          font-size: 11px;
        }

        .tag-more {
          font-size: 10px;
        }
      }

      .tag-item {
        font-size: 12px;
        font-weight: 500;
        cursor: pointer;
        border-radius: 12px;
        transition: all 0.2s ease;

        &:hover {
          box-shadow: 0 2px 6px rgb(0 0 0 / 15%);
          transform: translateY(-1px);
        }
      }

      .tag-more {
        font-size: 11px;
        border-radius: 12px;
        opacity: 0.8;
      }
    }

    .article-meta {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 8px;

      @media (width <= 768px) {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
      }

      // 当没有作者信息时，时间在左统计在右
      &.no-author {
        align-items: center;
        justify-content: space-between;

        @media (width <= 768px) {
          flex-direction: column;
          gap: 8px;
          align-items: stretch;

          .time-section {
            align-items: center;
            order: 1;
          }

          .article-stats {
            justify-content: center;
            order: 2;
          }
        }
      }

      .author-info {
        display: flex;
        gap: 8px;
        align-items: center;
        padding: 4px 8px;
        margin: -4px -8px;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.3s ease;

        &:hover {
          background: var(--el-fill-color-light);

          .author-name {
            color: var(--el-color-primary);
          }
        }

        .author-avatar {
          flex-shrink: 0;
        }

        .author-name {
          font-size: 13px;
          font-weight: 500;
          color: var(--el-text-color-regular);
          transition: color 0.3s ease;
        }
      }

      // 时间区域样式
      .time-section {
        display: flex;
        flex-direction: column;
        gap: 4px;
        align-items: flex-start;
        justify-content: center;

        .stat-item {
          display: flex;
          gap: 4px;
          align-items: center;
          font-size: 14px;
          color: var(--el-text-color-placeholder);

          .iconify {
            font-size: 14px;
            color: var(--el-text-color-placeholder);
          }

          &.interaction-time-item {
            color: var(--el-color-primary);

            .iconify {
              color: var(--el-color-primary);
            }
          }
        }
      }

      // 统计区域样式
      .article-stats {
        display: flex;
        gap: 12px;
        align-items: center;

        @media (width <= 768px) {
          flex-wrap: wrap;
          gap: 8px;
        }

        .stat-item {
          display: flex;
          gap: 4px;
          align-items: center;
          font-size: 14px;
          color: var(--el-text-color-secondary);

          .iconify {
            font-size: 14px;
            transition: all 0.2s ease;

            &.clickable {
              color: var(--el-color-primary);
              cursor: pointer;

              &:hover {
                color: var(--el-color-primary-dark-2);
                transform: scale(1.1);
              }

              &:active {
                transform: scale(0.95);
              }

              &.loading {
                pointer-events: none;
                cursor: not-allowed;
                opacity: 0.6;
              }
            }
          }

          .like-icon {
            width: 14px;
            height: 14px;
            color: var(--el-text-color-secondary);
            transition: all 0.2s ease;

            &.clickable {
              color: var(--el-color-danger);
              cursor: pointer;

              &:hover {
                color: var(--el-color-danger-dark-2);
                transform: scale(1.1);
              }

              &:active {
                transform: scale(0.95);
              }

              &.loading {
                pointer-events: none;
                cursor: not-allowed;
                opacity: 0.6;
              }
            }
          }

          &.interactive {
            position: relative;
          }
        }
      }
    }
  }
}
</style>
